// pages/list/list.js
const fetch = require('../../utils/fetch.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        category: '',
        shops: [],
        pageIndex: 0,
        pageSize: 20,
        hasMore: true,
        searchName: ''
    },
    loadMore: function() {
        // console.log(1);
        // console.log(this.data.hasMore);

        if (!this.data.hasMore) return;
        let pageIndex = this.data.pageIndex;
        let pageSize = this.data.pageSize;
        let params = { _page: ++pageIndex, _limit: pageSize };
        return fetch(`categories/${this.data.category.id}/shops`, params).then(res => {
            // console.log(res.header['x-total-count']);
            var totalCount = parseInt(res.header['x-total-count']);
            var shops = this.data.shops.concat(res.data);
            var hasMore = pageSize * pageIndex < totalCount;
            this.setData({
                shops,
                pageIndex,
                hasMore
            })
        });
    },
    inputHandle: function(e) {
        //更新数据
        this.setData({
            searchName: e.detail.value
        })
    },
    searchShopHandle: function() {
        if (!this.data.searchName) return;
        fetch(`/categories/${this.data.category.id}/shops?_page=1&_limit=1&q=${this.data.searchName}`).then(res => {
            console.log(res.data);
            var shops = res.data;
            this.setData({
                shops,
                searchName: '',
                hasMore: false
            });
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        fetch(`categories/${options.cat}`).then(res => {
            this.setData({
                category: res.data
            });
            wx.setNavigationBarTitle({ //setNavigationBarTitle是在页面渲染完成后去设置的
                title: res.data.name
            });
            //请求商家数据
            this.loadMore()
        })

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {
        if (this.data.category.name) {
            wx.setNavigationBarTitle({ //setNavigationBarTitle是在页面渲染完成后去设置的
                title: this.data.category.name
            })
        }
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        //重新加载数据
        this.setData({
            shops: [],
            pageIndex: 0,
            hasMore: true
        })
        this.loadMore().then(() => wx.stopPullDownRefresh());
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        //下拉加载下一页数据
        this.loadMore();
    }
})